import React, { useState, useEffect, useRef } from 'react';
import { Button, Modal, Form, Input, Switch, message, Space, Tag, Select, InputNumber, Row, Col } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import type { ProTableProps } from '@ant-design/pro-components';
import ApiService, { Product, Category, ProductImage } from '../../services/api';
import SimpleRichTextEditor from '../SimpleRichTextEditor';
import ImageUpload from '../ImageUpload';

const { TextArea } = Input;
const { Option } = Select;

interface ProductForm {
  name: string;
  description: string;
  price: number;
  original_price?: number;
  category_id: number;
  is_active: boolean;
  sort_order: number;
  rich_content?: string;
  specifications?: string;
}

const ProductManagement: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [productImages, setProductImages] = useState<ProductImage[]>([]);
  const [form] = Form.useForm();
  const actionRef = useRef<ActionType>();

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      const categoriesData = await ApiService.getCategories();
      setCategories(categoriesData.filter(cat => cat.is_active));
    } catch (error) {
      console.error('获取分类失败:', error);
      message.error('获取分类失败');
    }
  };

  // ProTable请求函数
  const request: ProTableProps<Product, any>['request'] = async (params, sort, filter) => {
    try {
      const queryParams: any = {
        skip: ((params.current || 1) - 1) * (params.pageSize || 10),
        limit: params.pageSize || 10,
      };

      // 添加分类筛选
      if (params.category_id) {
        queryParams.category_id = params.category_id;
      }

      // 添加名称搜索
      if (params.name) {
        queryParams.name = params.name;
      }

      const response = await ApiService.getProducts(queryParams);
      
      return {
        data: response.items || [],
        success: true,
        total: response.total || 0,
      };
    } catch (error) {
      console.error('获取产品列表失败:', error);
      message.error('获取产品列表失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const handleCreate = () => {
    setEditingProduct(null);
    setProductImages([]);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = async (product: Product) => {
    setEditingProduct(product);
    
    // 获取商品详情
    try {
      const detailData = await ApiService.getProductDetail(product.id);
      
      // 设置所有表单数据（包括基本信息和详情）
      form.setFieldsValue({
        name: product.name,
        description: product.description,
        price: product.price,
        original_price: product.original_price,
        category_id: product.category_id,
        is_active: product.is_active,
        sort_order: product.sort_order,
        rich_content: detailData.rich_content || '',
        specifications: detailData.specifications || '',
      });
    } catch (error) {
      console.error('获取商品详情失败:', error);
      // 如果获取详情失败，至少设置基本信息
      form.setFieldsValue({
        name: product.name,
        description: product.description,
        price: product.price,
        original_price: product.original_price,
        category_id: product.category_id,
        is_active: product.is_active,
        sort_order: product.sort_order,
        rich_content: '',
        specifications: '',
      });
    }

    // 加载商品图片
    await loadProductImages(product.id);

    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await ApiService.deleteProduct(id);
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: ProductForm) => {
    try {
      let productId: number;
      
      // 分离基本信息和详情信息
      const basicInfo = {
        name: values.name,
        description: values.description,
        price: values.price,
        original_price: values.original_price,
        category_id: values.category_id,
        is_active: values.is_active,
        sort_order: values.sort_order,
      };
      
      if (editingProduct) {
        await ApiService.updateProduct(editingProduct.id, basicInfo);
        productId = editingProduct.id;
        message.success('更新成功');
      } else {
        const newProduct = await ApiService.createProduct(basicInfo);
        productId = newProduct.id;
        message.success('创建成功');
      }
      
      // 保存商品详情
      const detailValues = {
        rich_content: values.rich_content || '',
        specifications: values.specifications || '',
      };
      
      if (detailValues.rich_content || detailValues.specifications) {
        try {
          await ApiService.updateProductDetail(productId, detailValues);
        } catch (error) {
          console.error('保存商品详情失败:', error);
        }
      }
      
      // 如果上传了图片但没有关联到商品，现在关联
      if (productImages.length > 0 && productImages.some(img => !img.product_id)) {
        try {
          // 关联所有未关联的图片到商品
          const unassociatedImages = productImages.filter(img => !img.product_id);
          for (const image of unassociatedImages) {
            await ApiService.associateImageWithProduct(image.id, productId);
          }
          message.success('图片关联成功');
        } catch (error) {
          console.error('关联图片失败:', error);
          message.error('图片关联失败');
        }
      }
      
      // 关闭弹窗
      setModalVisible(false);
      
      // 刷新数据
      actionRef.current?.reload();
      
      // 清空状态
      setProductImages([]);
    } catch (error: any) {
      console.error('操作失败:', error);
      message.error(error.message || '操作失败');
    }
  };

  const handleImagesUploaded = (images: ProductImage[]) => {
    setProductImages(prev => [...prev, ...images]);
  };

  const handleImagesDeleted = (imageIds: number[]) => {
    setProductImages(prev => prev.filter(img => !imageIds.includes(img.id)));
  };

  const loadProductImages = async (productId: number) => {
    try {
      const images = await ApiService.getImages(productId);
      setProductImages(images);
    } catch (error) {
      console.error('获取商品图片失败:', error);
    }
  };

  // 定义ProTable列
  const columns: ProColumns<Product>[] = [
    {
      title: '商品图片',
      dataIndex: 'first_image_url',
      key: 'image',
      width: 80,
      search: false,
      render: (_, record) => (
        <div style={{ textAlign: 'center' }}>
          {record.first_image_url ? (
            <img
              src={`http://101.33.122.140:8000${record.first_image_url}`}
              alt={record.name}
              style={{
                width: '50px',
                height: '50px',
                objectFit: 'cover',
                borderRadius: '4px',
                border: '1px solid #d9d9d9'
              }}
            />
          ) : (
            <div
              style={{
                width: '50px',
                height: '50px',
                backgroundColor: '#f5f5f5',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: '4px',
                border: '1px solid #d9d9d9',
                color: '#999',
                fontSize: '12px'
              }}
            >
              无图
            </div>
          )}
        </div>
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      ellipsis: true,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 250,
      ellipsis: true,
      search: false,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 120,
      search: false,
      render: (_, record) => (
        <div>
          <div className="current-price">¥{record.price.toFixed(2)}</div>
          {record.original_price && record.original_price > record.price && (
            <div className="original-price">¥{record.original_price.toFixed(2)}</div>
          )}
        </div>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category_id',
      key: 'category_id',
      width: 120,
      valueType: 'select',
      valueEnum: categories.reduce((acc, cat) => {
        acc[cat.id] = { text: cat.name };
        return acc;
      }, {} as Record<number, { text: string }>),
      render: (_, record) => {
        const category = categories.find(cat => cat.id === record.category_id);
        return category ? category.name : '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      width: 80,
      search: false,
      render: (_, record) => (
        <Tag color={record.is_active ? 'green' : 'red'}>
          {record.is_active ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      search: false,
      render: (_, record) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="default"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="product-management">
      <div className="page-header" style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: '20px' 
      }}>
        <h2>商品管理</h2>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleCreate}
        >
          新建商品
        </Button>
      </div>

      <ProTable<Product>
        columns={columns}
        actionRef={actionRef}
        request={request}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          collapsed: false,
          collapseRender: false,
          searchText: '搜索',
          resetText: '重置',
        }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        toolBarRender={false}
        dateFormatter="string"
        headerTitle="商品列表"
      />

      <Modal
        title={editingProduct ? '编辑商品' : '新建商品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={1200}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称!' }]}
              >
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
            
            <Col span={12}>
              <Form.Item
                name="category_id"
                label="所属分类"
                rules={[{ required: true, message: '请选择分类!' }]}
              >
                <Select placeholder="请选择分类">
                  {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格!' }]}
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="请输入价格"
                />
              </Form.Item>
            </Col>
            
            <Col span={12}>
              <Form.Item
                name="original_price"
                label="原价"
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="请输入原价（可选）"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="商品描述"
            rules={[{ required: true, message: '请输入商品描述!' }]}
          >
            <TextArea
              rows={3}
              placeholder="请输入商品描述"
            />
          </Form.Item>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="sort_order"
                label="排序"
                initialValue={0}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="排序值，数字越小越靠前"
                />
              </Form.Item>
            </Col>
            
            <Col span={12}>
              <Form.Item
                name="is_active"
                label="是否启用"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item label="商品图片">
            <ImageUpload
              productId={editingProduct?.id}
              onImagesUploaded={handleImagesUploaded}
              onImagesDeleted={handleImagesDeleted}
              maxCount={10}
              disabled={false}
            />
            {!editingProduct && (
              <div style={{ marginTop: 8, color: '#999', fontSize: '12px' }}>
                提示：可以先上传图片，保存商品信息后会自动关联
              </div>
            )}
          </Form.Item>

          <Form.Item
            name="rich_content"
            label="商品详情"
          >
            <SimpleRichTextEditor
              value={form.getFieldValue('rich_content') || ''}
              onChange={(html: string) => form.setFieldValue('rich_content', html)}
              height={300}
              placeholder="请输入商品详细信息..."
              key={editingProduct?.id || 'new'} // 添加key确保组件重新渲染
            />
          </Form.Item>

          <Form.Item
            name="specifications"
            label="商品规格"
          >
            <TextArea
              rows={4}
              placeholder="请输入商品规格信息"
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingProduct ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ProductManagement; 